package codeRandomThoughts.Test144二叉树的前序遍历;

import codeRandomThoughts.utils.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

//二刷
//统一迭代法
public class Solution4 {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();

        //用于存储遍历结点的过程
        Stack<TreeNode> stack = new Stack<>();

        if (root != null) stack.push(root);

        while (!stack.isEmpty()) {
            //前序遍历 根左右 反过来就是右左根
            TreeNode node = stack.pop();
            if (node != null) {
                if (node.right != null) {
                    stack.push(node.right);
                }
                if (node.left != null) {
                    stack.push(node.left);
                }
                stack.push(node);
                //此处的null只是一个标记位,表示下次取出这个节点时就要输出了
                stack.push(null);
            } else {
                TreeNode out = stack.pop();
                result.add(out.val);
            }
        }
        return result;
    }
}
